//
//  Statuses.swift
//  HJWeibo
//
//  Created by huangjiong on 16/2/5.
//  Copyright © 2016年 huangjiong. All rights reserved.
//

import UIKit
import SDWebImage

class Statuses: NSObject {
    
 /// 时间
    var create_at: String?
    
 /// id
    var id: Int = 0
    
 /// 内容
    var text: String?
    
 /// 来源
    var source: String?{
        didSet {
            //1.截取字符串
            if let str = source
            {
                if str == ""
                {
                    return
                }
                //1.1开始位置
                let startLocation = (str as NSString).rangeOfString(">").location + 1
                //1.2截取长度
                let length = (str as NSString).rangeOfString("<", options: NSStringCompareOptions.BackwardsSearch).location - startLocation
                //1.3截取
                source = "来自 " + (str as NSString).substringWithRange(NSMakeRange(startLocation, length))
            }
        }
    }
 /// 图片数组
    var pic_urls: [[String: AnyObject]]?
        {
        didSet{
            //1.先初始化保存图片url的数组
            storedPicURLs = [NSURL]()
            //通过遍历获取url,添加保存到数组当中
            for dict in pic_urls!
            {
                if let urlStr = dict["thumbnail_pic"]
                {
                    let url = NSURL(string: urlStr as! String)
                    storedPicURLs?.append(url!)
                }
            }
        }
    }
    
    /// 保存所有图片的url
    var storedPicURLs: [NSURL]?
    /// 用户
    var user: User?
    
    
    
    /**
     定义一个字典转模型方法
     
     - parameter dict: 包含模型数据的字典
     
     - returns: 无返回值
     */
    init(dict:[String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forKey key: String) {
        
        if key == "user"
        {
            user = User(dict:value as! [String: AnyObject])
            return
        }
        super.setValue(value, forKey: key)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    
    /**
     外部使用方法,用于请求数据,获取数据模型
     
     - parameter finished: <#finished description#>
     */
    class func loadStatuses(finished:(models:[Statuses]?,error:NSError?)->())
    {
        let path = "2/statuses/home_timeline.json"
        let parameters = ["access_token":UserAccount.loadAccount()!.access_token!]
        //网络请求
        HJNetworkManager.sharedManager().GET(path, parameters: parameters, progress: { (_) -> Void in
            
            }, success: { (_, JSON) -> Void in
                //1.创建数据模型
                var models = [Statuses]()
                for dict in JSON!["statuses"] as! [[String: AnyObject]]
                {
                    let model = Statuses(dict: dict)
                    models.append(model)
                }
                
                //去下载图片
                cahesStatusImages(models, finished: finished)
                
                
            }) { (_, error) -> Void in
                finished(models: nil, error: error)
        }
    }
    
    /**
     内部控制方法,用于下载图片
     
     - parameter list:     <#list description#>
     - parameter finished: <#finished description#>
     */
    class func cahesStatusImages(list: [Statuses],finished:(models:[Statuses]?,error:NSError?)->()){
        //1.创建一个组
        let group = dispatch_group_create()
        
        //2.缓存图片
        for status in list
        {
            for url in status.storedPicURLs!
            {
                //2.1 将当前下载操作添加到组中
                dispatch_group_enter(group)
                //2.2下载图片
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (_, _, _, _, _) -> Void in
                    
                    //2.3下载完成,就退出当前组
                    dispatch_group_leave(group)
                })
            }
        }
        //3.所有图片下载完成后,再回到主线程
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            
            //回调
            finished(models: list, error: nil)
        }
    
    }

}
